package com.guozcc.gateway.autopredicates;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;


/**
 * 自定义断言
 *      1、检测Header字段
 *      2、从指定字段获取值，与指定值匹配，相等则断言成功
 */
@Component
public class AutoHeaderRoutePredicateFactory extends AbstractRoutePredicateFactory<AutoHeaderRoutePredicateFactory.Config> {
    private final Logger log = LoggerFactory.getLogger(this.getClass());


    public static final String PARAM = "param";
    public static final String VALUE = "value";

    public AutoHeaderRoutePredicateFactory() {
        super(AutoHeaderRoutePredicateFactory.Config.class);
    }

    public List<String> shortcutFieldOrder() {
        return Arrays.asList("param", "value");
    }

    @Override
    public Predicate<ServerWebExchange> apply(AutoHeaderRoutePredicateFactory.Config config) {
        String param = config.getParam();
        String value = config.getValue();
        return exchange -> {
            if(StringUtils.isEmpty(param)){
                log.info("param 不允许为空");
                return false;
            }
            if(StringUtils.isEmpty(value)){
                log.info("value 不允许为空");
                return false;
            }
            List<String> strings = exchange.getRequest().getHeaders().get(param);
            if(strings==null){
                return false;
            }
            Optional<Boolean> reduce = strings.stream()
                    .map(s -> s.equals(value))
                    .reduce((result, element) -> result || element);
            if(reduce.isPresent()){
                return reduce.get();
            }else {
                return false;
            }
        };
    }

    @Validated
    public static class Config {
        @NotNull
        private String param;
        @NotNull
        private String value;

        public Config() {}

        public Config(@NotNull String param, @NotNull String value) {
            this.param = param;
            this.value = value;
        }

        public String getParam() {
            return param;
        }

        public void setParam(String param) {
            this.param = param;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }

    }
}
